<script setup>
import {useRouter} from 'vue-router';
import {ref, onMounted, reactive} from 'vue';
// 导入 Element Plus 组件（按需导入）
import {ElForm, ElFormItem, ElInput, ElButton, ElCard, ElMessage} from 'element-plus';
// 导入用户接口
import userApi from '../api/user_api.js';

// 组件挂载验证
onMounted(() => {
  console.log('注册组件已挂载');
});

// 路由实例
const router = useRouter();

// 1. 表单数据（与后端接收的字段名对齐）
const formData = reactive({
  user_name: '',       // 用户名
  user_id: '',         // 用户编号
  user_age: null,      // 用户年龄
  user_home: '',       // 家庭地址
  user_phone: '',      // 用户电话
  user_code: '',       // 密码
  confirmPassword: ''  // 确认密码
});

// 2. 表单引用（用于验证）
const registerForm = ref(null);

// 3. 表单验证规则
const formRules = {
  user_name: [
    {required: true, message: '请输入用户姓名', trigger: 'blur'}
  ],
  user_id: [
    {required: true, message: '请输入用户编号', trigger: 'blur'}
  ],
  user_age: [
    {required: true, message: '请输入用户年龄', trigger: 'blur'}
  ],
  user_home: [
    {required: true, message: '请输入家庭地址', trigger: 'blur'}
  ],
  user_phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的11位手机号', trigger: 'blur'}
  ],
  user_code: [
    {required: true, message: '请设置密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度 6-20 位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== formData.user_code) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 4. 提交表单
const handleSubmit = async () => {
  try {
    // 步骤1：表单验证
    await registerForm.value.validate();

    // 步骤2：准备提交给后端的数据
    const submitData = {
      user_name: formData.user_name,
      user_id: formData.user_id,
      user_age: formData.user_age,
      user_home: formData.user_home,
      user_phone: formData.user_phone,
      user_code: formData.user_code // 直接传递原密码
    };

    // 步骤3：调用注册接口，提交数据
    const result = await userApi.add(submitData);

    // 步骤4：注册成功，跳转登录页
    if (result) {
      ElMessage.success('注册成功，请登录');
      router.push('/userlogin');
    }
  } catch (error) {
    // 错误处理
    if (error.name === 'Error' && error.message.includes('validation')) {
      // 表单验证失败，Element 会自动提示，无需额外处理
      return;
    }
    ElMessage.error(error.message || '注册失败，请稍后重试');
  }
};

// 5. 重置表单
const handleReset = () => {
  registerForm.value.resetFields();
  ElMessage.info('表单已重置');
};

// 6. 跳转到登录页
const toLogin = () => {
  router.push('/userlogin');
};
</script>

<template>
  <div class="register-container">
    <!-- 背景图 -->
    <div class="bg-image"></div>

    <!-- 注册表单卡片 -->
    <el-card class="register-card" shadow="hover">
      <div class="register-header">
        <img src="@/assets/logo.png" alt="抱抱窝logo" class="logo"/>
        <h2 class="title">用户注册</h2>
      </div>

      <!-- 表单 -->
      <el-form
          ref="registerForm"
          :model="formData"
          :rules="formRules"
          label-width="110px"
          class="register-form"
      >
        <!-- 用户姓名 -->
        <el-form-item label="用户姓名" prop="user_name">
          <el-input
              v-model="formData.user_name"
              placeholder="请输入您的姓名"
              maxlength="20"
          ></el-input>
        </el-form-item>

        <!-- 用户编号 -->
        <el-form-item label="用户编号" prop="user_id">
          <el-input
              v-model="formData.user_id"
              placeholder="请输入用户编号（如 U2024001）"
              maxlength="10"
          ></el-input>
        </el-form-item>

        <!-- 用户年龄 -->
        <el-form-item label="用户年龄" prop="user_age">
          <el-input
              v-model.number="formData.user_age"
              type="number"
              placeholder="请输入年龄"
              min="1"
              max="120"
          ></el-input>
        </el-form-item>

        <!-- 家庭地址 -->
        <el-form-item label="家庭地址" prop="user_home">
          <el-input
              v-model="formData.user_home"
              placeholder="请输入详细家庭地址"
              maxlength="100"
          ></el-input>
        </el-form-item>

        <!-- 用户电话 -->
        <el-form-item label="用户电话" prop="user_phone">
          <el-input
              v-model="formData.user_phone"
              placeholder="请输入11位手机号码"
              maxlength="11"
          ></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="设置密码" prop="user_code">
          <el-input
              v-model="formData.user_code"
              type="password"
              placeholder="请设置密码（6-20位）"
              maxlength="20"
          ></el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              maxlength="20"
          ></el-input>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button
              type="primary"
              @click="handleSubmit"
              class="submit-btn"
          >
            完成注册
          </el-button>
          <el-button
              type="default"
              @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>

        <!-- 登录链接 -->
        <div class="login-link">
          已有账号？<span @click="toLogin" class="link">立即登录</span>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
/* 基础布局 */
.register-container {
  position: relative;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

/* 背景图 */
.bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('@/assets/aa.gif') no-repeat center center;
  background-size: cover;
  z-index: 1;
  filter: brightness(0.9);
}

/* 注册卡片 */
.register-card {
  width: 100%;
  max-width: 500px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 30px;
  z-index: 2;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* 头部 logo 和标题 */
.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 0 auto 15px;
  object-fit: contain;
  background: #fff;
  padding: 5px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

/* 表单样式 */
.register-form {
  margin-top: 20px;
}

/* 按钮区域 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.submit-btn {
  width: 160px;
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

.link {
  color: #409eff;
  cursor: pointer;
  margin-left: 5px;
  transition: color 0.3s;
}

.link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 响应式适配（手机端） */
@media (max-width: 576px) {
  .register-card {
    padding: 20px 15px;
  }

  .form-actions {
    flex-direction: column;
  }

  .submit-btn {
    width: 100%;
  }
}
</style>